#include <render/UI/text/font.h>

#include <iostream>
#include <string>
#include <ft2build.h>
#include FT_FREETYPE_H

Font::Font ( std::string pathToFont ) {
	if(FT_Init_FreeType(&this->m_lib))
	{
		std::cerr << "Failed to init FreeType" << std::endl;
	}
	
	if(pathToFont.empty())
	{
		if(FT_New_Face(this->m_lib, "./fonts/OpenSans-Regular.ttf", 0, &this->m_face))
		{
			std::cerr << "Unable to load default font" << std::endl;
		}
	}
	else
	{
		if(FT_New_Face(this->m_lib, pathToFont.c_str(), 0, &this->m_face))
		{
			std::cerr << "Unable to load '" << pathToFont << "' font" << std::endl;
		}
	}

	FT_Set_Pixel_Sizes(this->m_face, 0, 48);

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	for(uint8_t i = 0; i < 128; i++)
	{
		if(FT_Load_Char(this->m_face, i, FT_LOAD_RENDER))
		{
			std::cerr << "Failed to load character " << i << std::endl;
			continue;
		}

		GLuint texture;
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			GL_RED,
			this->m_face->glyph->bitmap.width,
			this->m_face->glyph->bitmap.rows,
			0,
			GL_RED,
			GL_UNSIGNED_BYTE,
			this->m_face->glyph->bitmap.buffer
		);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

		ft_char_t ch = 
		{
			texture,
			glm::ivec2(this->m_face->glyph->bitmap.width, this->m_face->glyph->bitmap.rows),
			glm::ivec2(this->m_face->glyph->bitmap_left, this->m_face->glyph->bitmap_top),
			static_cast<unsigned int>(this->m_face->glyph->advance.x)
		};

		this->alphabet.insert(std::pair<GLchar, ft_char_t>(i, ch));
	}
}

Font::~Font () {
	FT_Done_Face(this->m_face);
	FT_Done_FreeType(this->m_lib);
}